#include "tcp_modbus.h"

el::TcpModbus::TcpModbus()
{
	msg_id_ = 0;
	buffer_ = new uint_8[65525 * 2];
	for (int i = 0; i < 65525 * 2; i++)
	{
		buffer_[i] = 1;
	}
}
el::TcpModbus::~TcpModbus()
{
	if (buffer_)
	{
		delete buffer_;
		buffer_ = NULL;
	}
}

bool el::TcpModbus::parseData(const uint_8* data, int len)
{
	bool res = true;
	int cmd = data[7];
	switch (cmd)
	{
	case 0x4:
	{
		frame_length_ = 9;
		for (int i = 0; i < 8; i++)
		{
			frame_[i] = data[i];
		}
		int addr = (data[8] << 8) + data[9];
		int num = (data[10] << 8) + data[11];
		for (int i = 0; i < num && i < 123/*(256-9)/2*/; i++)
		{
			frame_[9 + i * 2] = buffer_[(addr + i) * 2];
			frame_[9 + i * 2 + 1] = buffer_[(addr + i) * 2 + 1];
			frame_length_ += 2;
		}
		frame_[5] = 3 + frame_length_ - 9;
		frame_[8] = frame_length_ - 9;
		break;
	}
	case 0x10:
		break;
	default:
		res = false;
	}
	return res;
}
bool el::TcpModbus::writeRegister(int value, uint_16 r)
{
	int reg = r * 2;

	buffer_[reg] = *((uint_8*)(&value) + 3);
	buffer_[reg + 1] = *((uint_8*)(&value) + 2);
	buffer_[reg + 2] = *((uint_8*)(&value) + 1);
	buffer_[reg + 3] = *((uint_8*)(&value) + 0);
	return true;
}
bool el::TcpModbus::writeRegister(double value, uint_16 r)
{
	int reg = r * 2;
	buffer_[reg] = *((uint_8*)(&value) + 7);
	buffer_[reg + 1] = *((uint_8*)(&value) + 6);
	buffer_[reg + 2] = *((uint_8*)(&value) + 5);
	buffer_[reg + 3] = *((uint_8*)(&value) + 4);
	buffer_[reg + 4] = *((uint_8*)(&value) + 3);
	buffer_[reg + 5] = *((uint_8*)(&value) + 2);
	buffer_[reg + 6] = *((uint_8*)(&value) + 1);
	buffer_[reg + 7] = *((uint_8*)(&value) + 0);
	return true;
}
bool el::TcpModbus::writeRegister(bool value, uint_16 r)
{
	int reg = r * 2;
	buffer_[reg + 1] = *((uint_8*)(&value) + 0);
	return true;
}
bool el::TcpModbus::writeRegister(char* value, uint_16 r, int len)
{
	int reg = r * 2;
	for (int i = 0; i < len; i++)
	{
		buffer_[reg + i] = value[i];
	}
	return true;
}